package com.github.lhj.ftp;

import org.apache.commons.io.FileUtils;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.ssl.SslConfigurationFactory;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;

import java.io.File;
import java.net.URL;
import java.util.concurrent.ThreadLocalRandom;

public class FtpServerApplication {

    private static final int PORT = 2121;
    private static final int PORT_NUMBER = ThreadLocalRandom.current().nextInt(2000, 3000);
    private static final String SERVER_JKS_RES = "wso2carbon.jks";
    public static final String KEYSTORE_PASSWORD = "wso2carbon";

    public static void main(String[] args) throws FtpException {

        FtpServerFactory serverFactory = new FtpServerFactory();
        //user manager
        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        userManagerFactory.setFile(new File("users.properties"));
        serverFactory.setUserManager(userManagerFactory.createUserManager());
        // set the port of the listener
        ListenerFactory factory = new ListenerFactory();
        factory.setPort(PORT);
        serverFactory.addListener("default", factory.createListener());
        // define SSL configuration
        URL serverJksResource = ClassLoader.getSystemClassLoader().getResource(SERVER_JKS_RES);
        SslConfigurationFactory ssl = new SslConfigurationFactory();
        File keyStoreFile = FileUtils.toFile(serverJksResource);
        ssl.setKeystoreFile(keyStoreFile);
        ssl.setKeystorePassword(KEYSTORE_PASSWORD);
        factory.setSslConfiguration(ssl.createSslConfiguration());
        FtpServer server = serverFactory.createServer();
        // start the server
        server.start();

    }
}
